﻿using System.Diagnostics;
using TomatoClock.Views;
using Timer = System.Threading.Timer;

namespace TomatoClock.Services
{
    public class ProcessMonitor : IProcessMonitor
    {
        private Timer monitorTimer;
        private List<string> disallowedProcesses;

        public event Action<string>? DisallowedProcessDetected;

        public ProcessMonitor(List<string> disallowedProcesses)
        {
            this.disallowedProcesses = disallowedProcesses;
            monitorTimer = new Timer(CheckProcesses, null, Timeout.Infinite, Timeout.Infinite);
        }

        public void StartMonitoring() => monitorTimer.Change(0, 1000);

        public void StopMonitoring() => monitorTimer.Change(Timeout.Infinite, Timeout.Infinite);

        private void CheckProcesses(object? state)
        {
            foreach (var process in Process.GetProcesses())
            {
                if (disallowedProcesses.Contains(process.ProcessName))
                {
                    using (var form = new MoniterForm())
                    {
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            DisallowedProcessDetected?.Invoke(process.ProcessName);
                        }
                        else
                        {
                            disallowedProcesses.Remove(process.ProcessName);
                        }
                    }
                    break;
                }
            }
        }
    }
}
